package com.gqs.ssh2.dao.impl;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;

import com.gqs.ssh2.dao.BaseDAO;
import com.gqs.ssh2.dao.CompanyDAO;
import com.gqs.ssh2.po.Company;
import com.gqs.ssh2.vo.Page;
import com.gqs.ssh2.vo.PageRequest;

/**
 *@Package com.gqs.ssh2.dao.impl
 *@Class com.gqs.ssh2.dao.impl.CompanyDAOImpl
 *@Description TODO
 *@author gqs
 *@date 2015年4月22日 下午7:59:25
 *@version V1.0
 *Copyright 葛葛梦工厂  Corporation 2015
 */
@Repository
public class CompanyDAOImpl extends BaseDAO implements CompanyDAO {

	/* (non-Javadoc)
	 * @see com.gqs.ssh2.dao.CompanyDAO#findAll()
	 */
	@SuppressWarnings("unchecked")
//	@Override
//	public List<Company> findAll() {
//		String hql="from Company";
//		return super.getHibernateTemplate().find(hql);
//	}

	/* (non-Javadoc)
	 * @see com.gqs.ssh2.dao.CompanyDAO#findByPageRequest(com.gqs.ssh2.vo.PageRequest)
	 */
	@Override
	public Page<Company> findByPageRequest(final PageRequest pageRequest) {
		HibernateTemplate  template =super.getHibernateTemplate();
		@SuppressWarnings("unchecked")
		
		List<Company> dataList = (List<Company>)template.executeFind(
				new HibernateCallback<List<Company>>() {
			@Override
			public List<Company> doInHibernate(Session session)
					throws HibernateException, SQLException {
				String hql="from Company c";
				Query query = session.createQuery(hql);
				query.setMaxResults(pageRequest.getSize());//?
				query.setFirstResult(pageRequest.getFirstResult());
				return query.list();
			}
		});
		
		
		Page<Company> page = new Page<Company>();
		page.setData(dataList);
		page.setIndex(pageRequest.getIndex());
		page.setSize(pageRequest.getSize());
		String hql = "select count(c) from Company c";
		Long total =(Long)template.find(hql).iterator().next();//???
		page.setTotal(total);
		return page;
	}
}
